package gradle.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;

import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;

@Slf4j
public class StreamUtil {

    /**
     * 去重方法
     *
     * @param keyExtractor
     * @param <T>
     * @return
     */
    public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
        Map<Object, Boolean> seen = new ConcurrentHashMap<>();
        return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
    }

    /**
     * 实体类 String类型字段  值null 转换为 空字符串
     */
    public static void stringNullToString(Object entity) {
        if (entity == null) {
            return;
        }

        Class<?> clazz = entity.getClass();
        Field[] fields = clazz.getDeclaredFields();

        for (Field field : fields) {
            // 允许访问私有字段
            field.setAccessible(true);

            try {
                if (field.getType() == String.class) {
                    if (field.get(entity) == null) {
                        // 设置为空字符串
                        field.set(entity, "");
                    }
                } else if (Collection.class.isAssignableFrom(field.getType())) {
                    Collection<?> collection = (Collection<?>) field.get(entity);
                    if (collection != null) {
                        for (Object item : collection) {
                            // 递归处理集合中的实体类
                            stringNullToString(item);
                        }
                    }
                } else {
                    // 如果字段是其他实体类，递归处理
                    stringNullToString(field.get(entity));
                }
            } catch (IllegalAccessException e) {
                log.error("StreamUtils.stringNullToString exception = {}", ExceptionUtils.getStackTrace(e));
            }
        }
    }

}
